<template>
  <div class="">
    <div class="flex justify-end">
      <button
        class="px-4 py-1 m-2
               text-sm text-purple-600 font-semibold
               rounded-full border border-purple-200
               enabled:hover:text-white enabled:hover:bg-purple-600
               disabled:cursor-not-allowed"
        :data-te-target="allowCreateCourse?'':'tooltip'"
        :title="allowCreateCourse?'':'only teacher can create course'"
        :disabled="allowCreateCourse"
        data-bs-toggle="modal" data-bs-target="#addCourseDialog">
        New
      </button>
    </div>
    <div class="">
      <div class="grid grid-cols-4 gap-3">
        <div v-for="course in courses" class="col" :key="course._id">
          <div class="border rounded justify-center py-4 px-2">
            <img v-if="course.poster" class="" :src="course.poster" />
            <div class="">
              <h5 class="text-2xl mb-1 font-sans">{{ course.coursename }}</h5>
              <span class="block p-1 font-serif">from {{ course.creator.username }}</span>
              <router-link :to="'/course/' + course._id"
              >
                <button
                  class="px-4 py-1 m-2
                        text-purple-600 font-semibold
                        rounded-full border border-purple-200
                        enabled:hover:text-white enabled:hover:bg-purple-600
                        disabled:cursor-not-allowed"
                >
                  View Course
                </button>
              </router-link>
            </div>
          </div>
        </div>
      </div>
    </div>
    <AddCourse id="addCourseDialog"></AddCourse>
  </div>
</template>

<script>
import CourseService from '@/services/CourseService';
import AddCourse from '@/components/AddCourse.vue';
import AC from '@/accesscontrol.js';

export default {
  name: 'Movies',
  props: {
    userId: '', // 用来判断是否需要对课程进行过滤
  },
  data() {
    return {
      courses: [],
    };
  },
  computed: {
    allowCreateCourse() {
      if (!this.$store.state.user.role) return true;
      const permission = AC.can(this.$store.state.user.role).createAny('course');
      return !permission.granted;
    },
  },
  components: {
    AddCourse,
  },
  created() {
    this.getCourses();
  },
  methods: {
    async getCourses() {
      var res;
      if (this.userId) {
        res = await CourseService.getCourses({id: this.userId});
      }
      else {
        res = await CourseService.getCourses();
      }
      this.courses = res.data;
      console.log("getCourses result", res);
    },
  },
};
</script>

<style scoped>
.card-body {
  text-align: left;
}
</style>
